Skip to content

Commit

Permalink
Avoid attribute indirection with env (#13212)
Browse files Browse the repository at this point in the history
  • Loading branch information
AA-Turner authored Jan 5, 2025
1 parent 56c9e32 commit 83bf866
Show file tree
Hide file tree
Showing 42 changed files with 181 additions and 160 deletions.
2 changes: 1 addition & 1 deletion doc/development/tutorials/examples/todo.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def process_todo_nodes(app, doctree, fromdocname):

# Replace all todolist nodes with a list of the collected todos.
# Augment each todo with a backlink to the original location.
env = app.builder.env
env = app.env

if not hasattr(env, 'todo_all_todos'):
env.todo_all_todos = []
Expand Down
20 changes: 11 additions & 9 deletions sphinx/builders/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@

if TYPE_CHECKING:
from collections.abc import Iterable, Sequence, Set
from pathlib import Path

from docutils.nodes import Node

Expand Down Expand Up @@ -242,8 +243,8 @@ def compile_catalogs(self, catalogs: set[CatalogInfo], message: str) -> None:
if not self.config.gettext_auto_build:
return

def cat2relpath(cat: CatalogInfo) -> str:
return relpath(cat.mo_path, self.env.srcdir).replace(os.path.sep, SEP)
def cat2relpath(cat: CatalogInfo, srcdir: Path = self.srcdir) -> str:
return relpath(cat.mo_path, srcdir).replace(os.path.sep, SEP)

logger.info(bold(__('building [mo]: ')) + message)
for catalog in status_iterator(
Expand Down Expand Up @@ -615,22 +616,23 @@ def merge(docs: list[str], otherenv: bytes) -> None:
@final
def read_doc(self, docname: str, *, _cache: bool = True) -> None:
"""Parse a file and add/update inventory entries for the doctree."""
self.env.prepare_settings(docname)
env = self.env
env.prepare_settings(docname)

# Add confdir/docutils.conf to dependencies list if exists
docutilsconf = os.path.join(self.confdir, 'docutils.conf')
if os.path.isfile(docutilsconf):
self.env.note_dependency(docutilsconf)
env.note_dependency(docutilsconf)

filename = str(self.env.doc2path(docname))
filename = str(env.doc2path(docname))
filetype = get_filetype(self.app.config.source_suffix, filename)
publisher = self.app.registry.get_publisher(self.app, filetype)
self.env.current_document._parser = publisher.parser
# record_dependencies is mutable even though it is in settings,
# explicitly re-initialise for each document
publisher.settings.record_dependencies = DependencyList()
with (
sphinx_domains(self.env),
sphinx_domains(env),
rst.default_role(docname, self.config.default_role),
):
# set up error_handler for the target document
Expand All @@ -642,11 +644,11 @@ def read_doc(self, docname: str, *, _cache: bool = True) -> None:
doctree = publisher.document

# store time of reading, for outdated files detection
self.env.all_docs[docname] = time.time_ns() // 1_000
env.all_docs[docname] = time.time_ns() // 1_000

# cleanup
self.env.current_document = _CurrentDocument()
self.env.ref_context.clear()
env.current_document = _CurrentDocument()
env.ref_context.clear()

self.write_doctree(docname, doctree, _cache=_cache)

Expand Down
2 changes: 1 addition & 1 deletion sphinx/builders/changes.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ def hl(no: int, line: str) -> str:
logger.info(bold(__('copying source files...')))
for docname in self.env.all_docs:
with open(
self.env.doc2path(docname), encoding=self.env.config.source_encoding
self.env.doc2path(docname), encoding=self.config.source_encoding
) as f:
try:
lines = f.readlines()
Expand Down
8 changes: 3 additions & 5 deletions sphinx/builders/gettext.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,10 +146,8 @@ class I18nBuilder(Builder):

def init(self) -> None:
super().init()
self.env.set_versioning_method(
self.versioning_method, self.env.config.gettext_uuid
)
self.tags = I18nTags()
self.env.set_versioning_method(self.versioning_method, self.config.gettext_uuid)
self.tags = self.app.tags = I18nTags()
self.catalogs: defaultdict[str, Catalog] = defaultdict(Catalog)

def get_target_uri(self, docname: str, typ: str | None = None) -> str:
Expand All @@ -174,7 +172,7 @@ def write_doc(self, docname: str, doctree: nodes.document) -> None:
if not _is_node_in_substitution_definition(node):
catalog.add(msg, node)

if 'index' in self.env.config.gettext_additional_targets:
if 'index' in self.config.gettext_additional_targets:
# Extract translatable messages from index entries.
for node, entries in traverse_translatable_index(doctree):
for entry_type, value, _target_id, _main, _category_key in entries:
Expand Down
2 changes: 1 addition & 1 deletion sphinx/builders/html/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -771,7 +771,7 @@ def write_domain_indices(self) -> None:

def copy_image_files(self) -> None:
if self.images:
stringify_func = ImageAdapter(self.app.env).get_original_image_uri
stringify_func = ImageAdapter(self.env).get_original_image_uri
ensuredir(self._images_dir)
for src in status_iterator(
self.images,
Expand Down
2 changes: 1 addition & 1 deletion sphinx/builders/latex/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -476,7 +476,7 @@ def copy_latex_additional_files(self) -> None:

def copy_image_files(self) -> None:
if self.images:
stringify_func = ImageAdapter(self.app.env).get_original_image_uri
stringify_func = ImageAdapter(self.env).get_original_image_uri
for src in status_iterator(
self.images,
__('copying images... '),
Expand Down
2 changes: 1 addition & 1 deletion sphinx/builders/texinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ def copy_assets(self) -> None:

def copy_image_files(self, targetname: str) -> None:
if self.images:
stringify_func = ImageAdapter(self.app.env).get_original_image_uri
stringify_func = ImageAdapter(self.env).get_original_image_uri
for src in status_iterator(
self.images,
__('copying images... '),
Expand Down
2 changes: 1 addition & 1 deletion sphinx/directives/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ def run(self) -> list[Node]:
finally:
# Private attributes for ToC generation. Will be modified or removed
# without notice.
if self.env.config.toc_object_entries:
if self.config.toc_object_entries:
signode['_toc_parts'] = self._object_hierarchy_parts(signode)
signode['_toc_name'] = self._toc_entry_name(signode)
else:
Expand Down
7 changes: 4 additions & 3 deletions sphinx/domains/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ class Domain:
data_version = 0

def __init__(self, env: BuildEnvironment) -> None:
domain_data: dict[str, dict[str, Any]] = env.domaindata
self.env: BuildEnvironment = env
self._role_cache: dict[str, RoleFunction] = {}
self._directive_cache: dict[str, type[Directive]] = {}
Expand All @@ -119,13 +120,13 @@ def __init__(self, env: BuildEnvironment) -> None:
self.roles = dict(self.roles)
self.indices = list(self.indices)

if self.name not in env.domaindata:
if self.name not in domain_data:
assert isinstance(self.initial_data, dict)
new_data = copy.deepcopy(self.initial_data)
new_data['version'] = self.data_version
self.data = env.domaindata[self.name] = new_data
self.data = domain_data[self.name] = new_data
else:
self.data = env.domaindata[self.name]
self.data = domain_data[self.name]
if self.data['version'] != self.data_version:
raise OSError('data of %r domain out of date' % self.label)
for name, obj in self.object_types.items():
Expand Down
16 changes: 8 additions & 8 deletions sphinx/domains/c/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ def describe_signature(
ast.describe_signature(signode, 'lastIsName', self.env, options)

def run(self) -> list[Node]:
env = self.state.document.settings.env # from ObjectDescription.run
env = self.env
if env.current_document.c_parent_symbol is None:
root = env.domaindata['c']['root_symbol']
env.current_document.c_parent_symbol = root
Expand All @@ -235,16 +235,16 @@ def handle_signature(self, sig: str, signode: TextElement) -> ASTDeclaration:
parent_symbol: Symbol = self.env.current_document.c_parent_symbol

max_len = (
self.env.config.c_maximum_signature_line_length
or self.env.config.maximum_signature_line_length
self.config.c_maximum_signature_line_length
or self.config.maximum_signature_line_length
or 0
)
signode['multi_line_parameter_list'] = (
'single-line-parameter-list' not in self.options
and (len(sig) > max_len > 0)
)

parser = DefinitionParser(sig, location=signode, config=self.env.config)
parser = DefinitionParser(sig, location=signode, config=self.config)
try:
ast = self.parse_definition(parser)
parser.assert_end()
Expand Down Expand Up @@ -400,7 +400,7 @@ def run(self) -> list[Node]:
stack: list[Symbol] = []
else:
parser = DefinitionParser(
self.arguments[0], location=self.get_location(), config=self.env.config
self.arguments[0], location=self.get_location(), config=self.config
)
try:
name = parser.parse_namespace_object()
Expand All @@ -427,7 +427,7 @@ def run(self) -> list[Node]:
if self.arguments[0].strip() in {'NULL', '0', 'nullptr'}:
return []
parser = DefinitionParser(
self.arguments[0], location=self.get_location(), config=self.env.config
self.arguments[0], location=self.get_location(), config=self.config
)
try:
name = parser.parse_namespace_object()
Expand Down Expand Up @@ -567,7 +567,7 @@ def apply(self, **kwargs: Any) -> None:
sig = node.sig
parent_key = node.parentKey
try:
parser = DefinitionParser(sig, location=node, config=self.env.config)
parser = DefinitionParser(sig, location=node, config=self.config)
name = parser.parse_xref_object()
except DefinitionError as e:
logger.warning(e, location=node)
Expand Down Expand Up @@ -716,7 +716,7 @@ def __init__(self, asCode: bool) -> None:
def run(self) -> tuple[list[Node], list[system_message]]:
text = self.text.replace('\n', ' ')
parser = DefinitionParser(
text, location=self.get_location(), config=self.env.config
text, location=self.get_location(), config=self.config
)
# attempt to mimic XRefRole classes, except that...
try:
Expand Down
14 changes: 7 additions & 7 deletions sphinx/domains/cpp/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ def add_target_and_index(
break
if not is_in_concept and 'no-index-entry' not in self.options:
stripped_name = name
for prefix in self.env.config.cpp_index_common_prefix:
for prefix in self.config.cpp_index_common_prefix:
if name.startswith(prefix):
stripped_name = stripped_name[len(prefix) :]
break
Expand Down Expand Up @@ -308,7 +308,7 @@ def describe_signature(
ast.describe_signature(signode, 'lastIsName', self.env, options)

def run(self) -> list[Node]:
env = self.state.document.settings.env # from ObjectDescription.run
env = self.env
if env.current_document.cpp_parent_symbol is None:
root = env.domaindata['cpp']['root_symbol']
env.current_document.cpp_parent_symbol = root
Expand Down Expand Up @@ -348,16 +348,16 @@ def handle_signature(self, sig: str, signode: desc_signature) -> ASTDeclaration:
parent_symbol: Symbol = self.env.current_document.cpp_parent_symbol

max_len = (
self.env.config.cpp_maximum_signature_line_length
or self.env.config.maximum_signature_line_length
self.config.cpp_maximum_signature_line_length
or self.config.maximum_signature_line_length
or 0
)
signode['multi_line_parameter_list'] = (
'single-line-parameter-list' not in self.options
and (len(sig) > max_len > 0)
)

parser = DefinitionParser(sig, location=signode, config=self.env.config)
parser = DefinitionParser(sig, location=signode, config=self.config)
try:
ast = self.parse_definition(parser)
parser.assert_end()
Expand Down Expand Up @@ -440,7 +440,7 @@ def _toc_entry_name(self, sig_node: desc_signature) -> str:
if not sig_node.get('_toc_parts'):
return ''

config = self.env.config
config = self.config
objtype = sig_node.parent.get('objtype')
if config.add_function_parentheses and objtype in {'function', 'method'}:
parens = '()'
Expand Down Expand Up @@ -710,7 +710,7 @@ def apply(self, **kwargs: Any) -> None:
sig = node.sig
parent_key = node.parentKey
try:
parser = DefinitionParser(sig, location=node, config=self.env.config)
parser = DefinitionParser(sig, location=node, config=self.config)
ast, is_shorthand = parser.parse_xref_object()
parser.assert_end()
except DefinitionError as e:
Expand Down
6 changes: 3 additions & 3 deletions sphinx/domains/javascript.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,8 @@ def handle_signature(self, sig: str, signode: desc_signature) -> tuple[str, str]
signode['fullname'] = fullname

max_len = (
self.env.config.javascript_maximum_signature_line_length
or self.env.config.maximum_signature_line_length
self.config.javascript_maximum_signature_line_length
or self.config.maximum_signature_line_length
or 0
)
multi_line_parameter_list = (
Expand Down Expand Up @@ -238,7 +238,7 @@ def _toc_entry_name(self, sig_node: desc_signature) -> str:
if not sig_node.get('_toc_parts'):
return ''

config = self.env.config
config = self.config
objtype = sig_node.parent.get('objtype')
if config.add_function_parentheses and objtype in {'function', 'method'}:
parens = '()'
Expand Down
8 changes: 4 additions & 4 deletions sphinx/domains/python/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ def get_index_text(self, modname: str, name_cls: tuple[str, str]) -> str:
name, cls = name_cls
try:
clsname, methname = name.rsplit('.', 1)
if modname and self.env.config.add_module_names:
if modname and self.config.add_module_names:
clsname = f'{modname}.{clsname}'
except ValueError:
if modname:
Expand Down Expand Up @@ -357,7 +357,7 @@ def get_index_text(self, modname: str, name_cls: tuple[str, str]) -> str:
name, cls = name_cls
try:
clsname, attrname = name.rsplit('.', 1)
if modname and self.env.config.add_module_names:
if modname and self.config.add_module_names:
clsname = f'{modname}.{clsname}'
except ValueError:
if modname:
Expand Down Expand Up @@ -417,7 +417,7 @@ def get_index_text(self, modname: str, name_cls: tuple[str, str]) -> str:
name, cls = name_cls
try:
clsname, attrname = name.rsplit('.', 1)
if modname and self.env.config.add_module_names:
if modname and self.config.add_module_names:
clsname = f'{modname}.{clsname}'
except ValueError:
if modname:
Expand Down Expand Up @@ -457,7 +457,7 @@ def get_index_text(self, modname: str, name_cls: tuple[str, str]) -> str:
name, cls = name_cls
try:
clsname, attrname = name.rsplit('.', 1)
if modname and self.env.config.add_module_names:
if modname and self.config.add_module_names:
clsname = f'{modname}.{clsname}'
except ValueError:
if modname:
Expand Down
8 changes: 4 additions & 4 deletions sphinx/domains/python/_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,8 +286,8 @@ def handle_signature(self, sig: str, signode: desc_signature) -> tuple[str, str]
signode['fullname'] = fullname

max_len = (
self.env.config.python_maximum_signature_line_length
or self.env.config.maximum_signature_line_length
self.config.python_maximum_signature_line_length
or self.config.maximum_signature_line_length
or 0
)

Expand Down Expand Up @@ -321,7 +321,7 @@ def handle_signature(self, sig: str, signode: desc_signature) -> tuple[str, str]

if prefix:
signode += addnodes.desc_addname(prefix, prefix)
elif modname and add_module and self.env.config.add_module_names:
elif modname and add_module and self.config.add_module_names:
nodetext = f'{modname}.'
signode += addnodes.desc_addname(nodetext, nodetext)

Expand Down Expand Up @@ -474,7 +474,7 @@ def _toc_entry_name(self, sig_node: desc_signature) -> str:
if not sig_node.get('_toc_parts'):
return ''

config = self.env.config
config = self.config
objtype = sig_node.parent.get('objtype')
if config.add_function_parentheses and objtype in {'function', 'method'}:
parens = '()'
Expand Down
3 changes: 1 addition & 2 deletions sphinx/domains/rst.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,12 +84,11 @@ def _toc_entry_name(self, sig_node: desc_signature) -> str:
if not sig_node.get('_toc_parts'):
return ''

config = self.env.config
objtype = sig_node.parent.get('objtype')
*parents, name = sig_node['_toc_parts']
if objtype == 'directive:option':
return f':{name}:'
if config.toc_object_entries_show_parents in {'domain', 'all'}:
if self.config.toc_object_entries_show_parents in {'domain', 'all'}:
name = ':'.join(sig_node['_toc_parts'])
if objtype == 'role':
return f':{name}:'
Expand Down
4 changes: 2 additions & 2 deletions sphinx/domains/std/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,13 +258,13 @@ def handle_signature(self, sig: str, signode: desc_signature) -> str:
args = '[' + args

if count:
if self.env.config.option_emphasise_placeholders:
if self.config.option_emphasise_placeholders:
signode += addnodes.desc_sig_punctuation(',', ',')
signode += addnodes.desc_sig_space()
else:
signode += addnodes.desc_addname(', ', ', ')
signode += addnodes.desc_name(optname, optname)
if self.env.config.option_emphasise_placeholders:
if self.config.option_emphasise_placeholders:
add_end_bracket = False
if args:
if args[0] == '[' and args[-1] == ']':
Expand Down
Loading

0 comments on commit 83bf866

Please sign in to comment.